package cate.game.mail;

import cate.common.game.mail.MailCmd;
import cate.common.rpc.path.RpcCommonPath;
import cate.game.GameBody;
import cate.game.db.SaveConstants;
import cate.game.framework.ModuleMan;
import cate.game.mail.po.MailBox;
import cate.game.role.Role;
import cate.game.role.mail.Mail;
import cate.game.util.IntervalCounter;
import cp.solution.pattern.Result;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/** 邮件管理模块 */
public class MailManager extends ModuleMan {
    private final Map<String, MailBox> boxCache = new HashMap<>();

    public GmMailHandler gmMail;
    public BatchMailHandler batchMail = new BatchMailHandler(this);
    private MailCmdHandler mailCmd = new MailCmdHandler(this);

    public GameBody getGame() { return this.game; }

    public void setup(MailDataSource mds) {
        this.gmMail = new GmMailHandler(this, mds);
    }

    @Override
    public void initDependent() throws Exception {
        game.rpcRecv().onRequestResponseTemplate(RpcCommonPath.MAIL_SEND_TO_GAME, MailCmd.class, mailCmd::onRequest);
    }

    public void send(Role role, Mail mail) {
        send(role.getUid(), mail);
    }

    public void send(String masterIdHex, Mail mail) {
        if (!game.role.activeForOnlineRole(masterIdHex, e -> e.getMail().add(mail))) {
            getBox(masterIdHex, true).add(mail);
        }
    }

    /** 获取离线收件箱 */
    public synchronized MailBox getBox(String uid, boolean required) {
        MailBox box = boxCache.get(uid);
        if (box == null) {
            box = game.db.mailBox.find(uid);
            if (box != null) {
                box.initialize();
                boxCache.put(uid, box);
            }
        }
        if (required && box == null) {
            box = new MailBox();
            box.initialize();
            box.uid = uid;
            boxCache.put(uid, box);
        }
        return box;
    }

    @Override
    public synchronized void shutdown() {
        for (MailBox box : boxCache.values()) {
            if (box.isEmpty()) {
                game.db.mailBox.delete(box.uid);
            } else {
                game.db.mailBox.upsert(box);
            }
        }
        boxCache.clear();
    }

    private static final AtomicInteger IDX = new AtomicInteger(0);
    private final IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.MAIL_SAVE_SECONDS, IDX.getAndIncrement());
    public void tick(){
        if(saveTrigger.trigger()){
            long start = System.currentTimeMillis();
            shutdownSafe();
            log.debug("game mail定时保存完成, cost{} ms", System.currentTimeMillis() - start);
        }
    }
}